package com.seguriapp.dialogs;

import twitter4j.Twitter;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.seguriapp.R;
import com.seguriapp.sync.TwitterTask;

public class TwitterMessageDialog extends Dialog {

	private final Twitter mTwitter;
	private final Dialog twitterDialog;
	private final TextView counterText;
	private final Context mContext;

	public TwitterMessageDialog(final Activity context, final Twitter twitter,
			final String message) {
		super(context);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.twitter_message);
		mContext = context;
		mTwitter = twitter;

		final EditText messageBox = (EditText) this
				.findViewById(R.id.twitterMessage);
		messageBox.setText(message);

		messageBox.addTextChangedListener(messageBoxListener);

		counterText = (TextView) this.findViewById(R.id.counter);
		counterText.setText(String.valueOf(140 - message.length()));

		final Button btnTweet = (Button) this.findViewById(R.id.tweetButton);

		btnTweet.setOnClickListener(new Button.OnClickListener() {
			public void onClick(final View view) {
				if (messageBox.getText().length() <= 140) {
					final TwitterTask dataTask = new TwitterTask(context,
							mTwitter);
					dataTask.execute(messageBox.getText().toString());
					twitterDialog.dismiss();
				} else {
					Toast.makeText(mContext, "Tweet too large..",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		twitterDialog = this;

	}

	private final TextWatcher messageBoxListener = new TextWatcher() {

		public void afterTextChanged(final Editable message) {
			final int lengthMessage = 140 - message.length();
			counterText.setText(String.valueOf(lengthMessage));
			if (lengthMessage < 0) {
				counterText.setTextColor(mContext.getResources().getColor(
						R.color.TwitterCounterRed));
			} else {
				counterText.setTextColor(mContext.getResources().getColor(
						R.color.TwitterCounterBlack));
			}
		}

		public void beforeTextChanged(final CharSequence arg0, final int arg1,
				final int arg2, final int arg3) {
			// TODO Auto-generated method stub

		}

		public void onTextChanged(final CharSequence arg0, final int arg1,
				final int arg2, final int arg3) {
			// TODO Auto-generated method stub
		}
	};
}
